package com.dongnam.quanly.web.audit;

import java.util.List;
import java.util.Map;

import org.primefaces.model.LazyDataModel;
import org.primefaces.model.SortOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.dongnam.quanly.common.controller.AuditTrailLogController;
import com.dongnam.quanly.common.model.AuditTrailLog;
import com.dongnam.quanly.web.JSFUtility;

public class LazyAuditDataModel extends LazyDataModel<AuditTrailLog> {

	private static final long serialVersionUID = 1L;
	private static final Logger logger = LoggerFactory.getLogger(LazyAuditDataModel.class);

	public List<AuditTrailLog> list;

	public LazyAuditDataModel() {
	}

	public void init(AuditBean auditBean) {
		// AuditBean auditBean = JSFUtility.findBean(AuditBean.class);
		int count = (int) new AuditTrailLogController().findCountByFilters(auditBean.getFromDate(),
				auditBean.getToDate(), auditBean.getActioneeName(), auditBean.getActioneeIp(), auditBean.getScreenId(),
				auditBean.getActionCategory() != null ? auditBean.getActionCategory() : null,
				auditBean.getActionType() != null ? auditBean.getActionType() : null, auditBean.getResult(),
				auditBean.getObject(), auditBean.getObjectId());
		setRowCount(count);
		logger.debug("init: setRowCount = {}", count);

	}

	@Override
	public Object getRowKey(AuditTrailLog log) {
		return log.getId();
	}

	@Override
	public AuditTrailLog getRowData(String rowKey) {
		// logger.debug("once");
		return new AuditTrailLogController().findById(Long.parseLong(rowKey), false);
	}

	@Override
	public List<AuditTrailLog> load(int first, int pageSize, String sortField, SortOrder sortOrder,
			Map<String, Object> filters) {
		logger.debug("load (first = {}, pageSize = {}, sortField = {}, sortOrder = {})", new Object[] { first,
				pageSize, sortOrder.toString(), sortField });
		if (sortField == null) {
			sortField = "actionTime";
			sortOrder = SortOrder.DESCENDING;
		}
		AuditBean auditBean = JSFUtility.findBean(AuditBean.class);
		list = new AuditTrailLogController().findByFilters(pageSize, first / pageSize, auditBean.getFromDate(),
				auditBean.getToDate(), auditBean.getActioneeName(), auditBean.getActioneeIp(),
				auditBean.getScreenId() != null ? auditBean.getScreenId() : null,
				auditBean.getActionCategory() != null ? auditBean.getActionCategory() : null,
				auditBean.getActionType() != null ? auditBean.getActionType() : null, auditBean.getResult(), auditBean
						.getObject(), auditBean.getObjectId(), SortOrder.valueOf(sortOrder.name()).toString(),
				sortField);
		return list;
	}

}